package com.supermarket.api.service.impl;

import com.supermarket.api.bean.IdReq;
import com.supermarket.api.bean.cart.CartRes;
import com.supermarket.api.bean.cart.CreateCartReq;
import com.supermarket.api.bean.cart.UpdateNumberCartReq;
import com.supermarket.api.common.filters.UserCacheManage;
import com.supermarket.api.entity.CartEntity;
import com.supermarket.api.entity.ProductEntity;
import com.supermarket.api.entity.ProductSkuEntity;
import com.supermarket.api.repository.CartRepository;
import com.supermarket.api.repository.ProductRepository;
import com.supermarket.api.repository.ProductSkuRepository;
import com.supermarket.api.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 购物车服务层
 * @author 李其伟
 * @date 2023/11/10
 */
@Slf4j
@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Autowired
    private ProductRepository productRepository;

    @Autowired
    private ProductSkuRepository productSkuRepository;

    @Override
    public void create(CreateCartReq req) {
        Long userId = UserCacheManage.getUserIdCache();
        //查询购物车是否存在
        CartEntity cartEntity = cartRepository.findAllByUserIdAndSkuCode(userId,req.getSkuCode());
        if(cartEntity==null) {
            ProductEntity productEntity = productRepository.findAllBySku(req.getSku());
            CartEntity entity = new CartEntity();
            entity.setSku(req.getSku());
            entity.setSkuCode(req.getSkuCode());
            entity.setNumber(req.getNumber());
            entity.setShopId(productEntity.getShopId());
            entity.setUserId(userId);
            entity.setUpdateTime(new Date());
            cartRepository.save(entity);
        }else {
            cartEntity.setUpdateTime(new Date());
            cartEntity.setNumber((cartEntity.getNumber()+1));
            cartRepository.save(cartEntity);
        }
    }

    @Override
    public void updateNumber(UpdateNumberCartReq req) {
        Optional<CartEntity> optional = cartRepository.findById(req.getId());
        if(optional.isPresent()){
            CartEntity entity = optional.get();
            entity.setUpdateTime(new Date());
            entity.setNumber(req.getNumber());
            cartRepository.save(entity);
        }
    }

    @Override
    public void delete(IdReq req) {
        Optional<CartEntity> optional = cartRepository.findById(req.getId());
        if(optional.isPresent()){
            CartEntity entity = optional.get();
            cartRepository.delete(entity);
        }
    }

    @Override
    public void clear() {
        Long userId = UserCacheManage.getUserIdCache();
        List<CartEntity> list = cartRepository.findAllByUserIdOrderByUpdateTimeDesc(userId);
        if(!CollectionUtils.isEmpty(list)){
            cartRepository.deleteInBatch(list);
        }
    }

    @Override
    public List<CartRes> list() {
        Long userId = UserCacheManage.getUserIdCache();

        List<CartEntity> cartEntityList = cartRepository.findAllByUserIdOrderByUpdateTimeDesc(userId);

        //获取产品数据
        List<String> skuList = cartEntityList.stream().map(CartEntity::getSku).collect(Collectors.toList());
        List<ProductEntity> productEntityList = productRepository.findAllBySkuIn(skuList);
        Map<String,ProductEntity> productMap = productEntityList.stream().collect(Collectors.toMap(ProductEntity::getSku, entity ->entity));

        //获取产品sku数据
        List<String> skuCodeList = cartEntityList.stream().map(CartEntity::getSkuCode).collect(Collectors.toList());
        List<ProductSkuEntity> productSkuEntityList = productSkuRepository.findAllBySkuCodeIn(skuCodeList);
        Map<String,ProductSkuEntity> skuProductMap = productSkuEntityList.stream().collect(Collectors.toMap(ProductSkuEntity::getSkuCode, entity ->entity));

        //设置列表
        List<CartRes> cartResList = new ArrayList<>();
        for(CartEntity cartEntity : cartEntityList){
            CartRes cartRes = new CartRes();

            ProductEntity pe = productMap.get(cartEntity.getSku());
            if(pe==null){
                break;
            }
            BeanUtils.copyProperties(productMap.get(cartEntity.getSku()),cartRes);

            if(cartEntity.getSkuCode()!=null){
                ProductSkuEntity productSkuEntity = skuProductMap.get(cartEntity.getSkuCode());
                if(productSkuEntity.getPic()!=null){
                    cartRes.setPic(productSkuEntity.getPic());
                }
                cartRes.setPrice(productSkuEntity.getPrice());
                cartRes.setSkuCode(productSkuEntity.getSkuCode());
                cartRes.setSpData(productSkuEntity.getSpData());
            }

            cartRes.setId(cartEntity.getId());
            cartRes.setNumber(cartEntity.getNumber());
            cartRes.setUpdateTime(cartEntity.getUpdateTime());

            cartResList.add(cartRes);
        }

        return cartResList;
    }
}
